import reqwest from 'reqwest';
import CryptoJS from 'crypto-js';
import {browserHistory} from 'react-router';
import { notification } from 'antd';
const secret = 'huadan2017';

/**
 * 接口配置
 * @type {string}
 */
let apiUrl = 'http://127.0.0.1:8360';  //接口地址
let rbacApi = `${apiUrl}/rbac`;
let crudApi = `${apiUrl}/crud`;
export const api = {
  rbac:{
    login:`${rbacApi}/login`
  },
  crud:{
    add:`${crudApi}/add`,
    addMany:`${crudApi}/addMany`,
    update:`${crudApi}/update`,
    updateMany:`${crudApi}/updateMany`,
    create:`${crudApi}/create`,
    find:`${crudApi}/find`,
    select:`${crudApi}/select`,
    list:`${crudApi}/list`,
    del:`${crudApi}/del`,
    delMany:`${crudApi}/delMany`,
    increment:`${crudApi}/increment`,
    decrement:`${crudApi}/decrement`,
    sum:`${crudApi}/sum`,
    count:`${crudApi}/count`,
    avg:`${crudApi}/avg`,
    findRepeat:`${crudApi}/findRepeat`
  }
};

/**
 * 封装好的异步
 * @type {number}
 */
export const numsPerPage = 10; //分页查询每次查询数量
export const  request = (params) => {
  let data = {
    data:params.data,
    other:{
      token:localStorage.getItem('token'),
      columnId:localStorage.getItem('columnId')},
  };
  data = encrypted(data);
  // console.log(data);
  return new Promise(function (resolve,reject) {
    resolve(
      reqwest({
        url: params.url,
        method: 'post',
        crossOrigin:true,
        data: {data},
        type: 'json'
      })
    );
  });
};

/**
 * upload
 * @param url
 * @param params
 * @returns {Promise}
 */
export const upLoad = ( url,params = {} ) => {
  return new Promise(function (resolve,reject) {
    resolve(
      reqwest({
        url: url,
        method: 'get',
        crossOrigin:true,
        data: {data:JSON.stringify(params)},
        type: 'json',
      })
    );
  });
};


/**
 * 定义错误码，对应接口错误码
 * @type {string}
 */
let error = '1000 1001 400 403 404 500 503';
export const tips = (type,message='',description='') => {
  if(type.errno === 0){   //成功
    type = 'success';
    message = '操作成功';
  }else if(type.errno === 1001){
    localStorage.setItem('isLogin',false);
    location.reload();
  }else if(error.indexOf(type.errno) !== -1){
    description = type.errmsg;
    type = 'error';
    message = '操作失败';
  }
  notification[type]({
    message: message,
    description:description
  });

};

/**
 * encrypted
 * @param params
 * @returns {string}
 */
export const encrypted=(params)=>{
  return CryptoJS.AES.encrypt(JSON.stringify(params), secret).toString();
};

/**
 * decrypted
 * @param params
 */
export const decrypted=(params)=>{
  let bytes  = CryptoJS.AES.decrypt(params, secret);
  return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
};